/**
 * @Title: model.js
 * @Description: model
 * @author: Fanchao
 * @date: 2020/10/25 1:52 下午
 * @version V1.0
 */

import { pathToRegexp } from 'path-to-regexp';
import { message } from 'antd';
import {
    reqArticleDetail,
    reqArticleEdit,
} from 'api/index';

export default {
    namespace: 'articleDetail',
    state: {
        articleDetail: {},
        content: '',
    },
    reducers: {
        setArticleDetail(state, { payload: articleDetail }) {
            return { ...state, articleDetail };
        },
        setContent(state, { payload: content }) {
            return { ...state, content };
        },
    },
    effects: {
        * getArticleDetail({ payload }, { call, put, select }) {
            const result = yield call(reqArticleDetail, payload);
            if (result.status === 1) {
                const articleDetail = result.data;
                yield put({
                    type: 'setArticleDetail',
                    payload: articleDetail,
                });
                yield put({
                    type: 'setContent',
                    payload: articleDetail.content,
                });
            } else {
                message.error(result.message);
            }
        },
        * updateArticle({ payload, callback }, { call, put, select }) {
            const result = yield call(reqArticleEdit, payload);
            if (result.status === 1) {
                if (callback && typeof callback === 'function') {
                    callback(result);
                }
            } else {
                message.error(result.message);
            }
        },
    },
    subscriptions: {
        setup({ dispatch, history }) {
            history.listen(({ pathname, query }) => {
                if (pathToRegexp('/system-manage/article/edit').exec(pathname)) {
                    dispatch({
                        type: 'getArticleDetail',
                        payload: {
                            id: query.id,
                        },
                    });
                }
            });
        },
    },
};
